import React, { useState, useEffect } from 'react'
import { connect } from 'dva'
import request from '../utils/request';
import servicePath from '../config/apiUrl'

import styles from './styles/ArticleList.less'

import { List, Row, Col, Modal, message, Button, Switch } from 'antd';

const { confirm } = Modal;




const ArticleList = (props) => {  


  const [list, setList] = useState([])


  const getList = () => {
    request(servicePath.getArticleList, {
      method: "get",
      credentials: 'include'//同源跨域都携带cookies/session
    }).then(res => {
      console.log("res-------getlist-", res);
      if (res.data.code === "0000") {
        let slist = res.data.data;
        console.log("list", slist);
        setList(slist)
      }
    })
  }

  //删除文章的方法
  const delArticle = (id) => {
    confirm({
      title: '确定要删除这篇博客文章吗?',
      content: '如果你点击OK按钮，文章将会永远被删除，无法恢复。',
      onOk() {
        request(`${servicePath.delArticle}${id}`, {
          method: "get",
          credentials: 'include'//同源跨域都携带cookies/session
        }).then(
          res => {
            message.success('文章删除成功')
            getList()
          }
        )
      },
      onCancel() {
        message.success('没有任何改变')
      },
    });

  }


  //修改文章
  const updateArticle = (id, checked) => {
    props.history.push('/index/add/' + id)
  }

  useEffect(() => {
    getList();
  }, [])

  return (
    <div>
      <List
        header={
          <Row className={styles["list-div"]}>
            <Col span={8}>
              <b>标题</b>
            </Col>
            <Col span={3}>
              <b>类别</b>
            </Col>
            <Col span={3}>
              <b>发布时间</b>
            </Col>
            <Col span={3}>
              <b>浏览量</b>
            </Col>
            <Col span={4}>
              <b>操作</b>
            </Col>
          </Row>
        }
        bordered
        dataSource={list}
        renderItem={item => (
          <List.Item>
            <Row className={styles["list-div"]}>
              <Col span={8}>
                {item.title}
              </Col>
              <Col span={3}>
                {item.typeName}
              </Col>
              <Col span={3}>
                {item.addTime}
              </Col>
              <Col span={3}>
                {item.view_count}
              </Col>
              <Col span={4}>
                <Button type="primary" onClick={() => { updateArticle(item.id) }}>修改</Button>&nbsp;
                <Button onClick={() => { delArticle(item.id) }} >删除 </Button>
              </Col>
            </Row>

          </List.Item>
        )}
      />
    </div>
  )
}



ArticleList.protoTypes = {

}

export default connect()(ArticleList)
